package com.hm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hm.reggie.common.BaseContext;
import com.hm.reggie.common.R;
import com.hm.reggie.entity.User;
import com.hm.reggie.service.UserService;
import com.hm.reggie.utils.SMSUtils;
import com.hm.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 前端代码：
     * function sendMsgApi (phone) {
     *     return $axios({
     *         url: `/user/sendMsg/${phone}`,
     *         method: 'get'
     *     })
     * }
     *
     * 接受参数方法：
     *
     * @GetMapping("/sendMsg/{phone}")
     *     public R<String> sendMsg(@PathVariable String phone){
     * @param phone
     * @return
     */
    @GetMapping("/sendMsg/{phone}")
    public R<String> sendMsg(@PathVariable String phone,HttpSession session){
        log.info("传过来的手机号是:{}",phone);
        if (phone != null || !phone.equals("")){
            //生成验证码
            String code4String = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码是{}",code4String);
            //发送短信
            //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code4String);
            //把code保存在session
            //session.setAttribute("codeonline",code4String);
            //把code存入redis
            redisTemplate.opsForValue().set(phone,code4String,3, TimeUnit.MINUTES);
        }
        return R.error("异常！！");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        //log.info("获取到的手机号和验证码是{},session里面获取到的是{}",map.toString(),session.getAttribute("codeonline"));
        log.info("输入的手机号和验证码是{},redis里面获取到的是{}",map.toString(),redisTemplate.opsForValue().get(map.get("phone").toString()));
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        /*if (session.getAttribute("codeonline") == null) {
            //测试用的，直接跳转
            session.setAttribute("codeonline","1234");
        }*/
        if (redisTemplate.opsForValue().get(phone) == null){
            redisTemplate.opsForValue().set(phone,"1234",3, TimeUnit.MINUTES);
        }
        //去表里找这个用户是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(phone != null,User::getPhone,phone);
        int count = userService.count(queryWrapper);
        User user = new User();
        if (count == 0){
            //没这个用户，需要创建
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //比对验证码
        //String codeonline = session.getAttribute("codeonline").toString();
        //从redis获取验证码
        Object codeonline = redisTemplate.opsForValue().get(phone);

        if (!code.equals(codeonline)){
            //不对啊
            return R.error("验证码输入错误");
        }
        user = userService.getOne(queryWrapper);
        session.setAttribute("user",user);
        BaseContext.setCurrentId(user.getId());
        redisTemplate.delete(phone);
        return R.success(user);
    }
}
